package com.college.action.student;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.college.action.user.BaseAction;
import com.college.constant.AttachmentConstant;
import com.college.constant.SubmitStatusConstant;
import com.college.constant.SystemConstant;
import com.college.entity.Attachment;
import com.college.entity.Classes;
import com.college.entity.HomeWorkOrder;
import com.college.entity.JobLine;
import com.college.entity.User;
import com.college.entity.UserClasses;
import com.college.entity.vo.JsonVo;
import com.college.exception.UploadException;
import com.college.service.CommonStudentService;
import com.college.service.JobOrderService;
import com.college.service.SystemUserService;
import com.college.util.BaseUtils;

/**
 * @author bob
 * 
 */

@Controller
@RequestMapping("user/student")
public class StudentAction extends BaseAction {

	@Autowired
	private CommonStudentService commonStuAdminService;

	@Autowired
	private SystemUserService systemUserService;

	@Autowired
	private JobOrderService jobOrderService;

	/**
	 * 学生主页面
	 * 
	 * @param request
	 * @param classEntity
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "index.htm", method = RequestMethod.GET)
	public String teacherIndex(HttpServletRequest request, ModelMap modelMap)
			throws Exception {
		// 查询老师发布的作业信息
		User user = (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		// TODO 判断该用户是否已经加入班级。已经加入了就可以查询作业，否则提示先加入班级
		List<HomeWorkOrder> releasedHomeWorkList = commonStuAdminService
				.getReleasedHomeWorkList(user.getClassIdList().get(0),
						user.getUserId());

		List<String> jobOrderIdList;
		// 作业单关联附件信息
		jobOrderIdList = BaseUtils.getIds(releasedHomeWorkList);
		// jobOrderIds ="f95a97bc-4004-4300-bd1a-8f28a081ed64";
		List<Attachment> attachmentList = jobOrderService
				.getAttachmentListByJorOrderIds(jobOrderIdList);

		for (HomeWorkOrder homeWork : releasedHomeWorkList) {
			for (Attachment attachment : attachmentList) {
				if (homeWork.getJobOrderId().equals(
						attachment.getForeignKeyId())) {
					homeWork.setAttachment(attachment);
					break;
				}
			}
		}
		modelMap.put("releasedHomeWorkList", releasedHomeWorkList);

		return "student/pages/index";
	}

	/*	*//**
	 * 学生主页面
	 * 
	 * @param request
	 * @param classEntity
	 * @return
	 */
	/*
	 * @RequestMapping(value = "studentClasses.htm", method = RequestMethod.GET)
	 * public String studentClasses(HttpServletRequest request, ModelMap
	 * modelMap) { // 查询老师发布的作业信息 User user = (User)
	 * request.getSession().getAttribute( SystemConstant.SESSION_USER); //TODO
	 * 判断该用户是否已经加入班级。已经加入了就可以查询作业，否则提示先加入班级 String classId =
	 * "568daae1-85d8-4f95-a248-3173687b0e4a"; List<HomeWorkOrder>
	 * releasedHomeWorkList =
	 * commonStuAdminService.getReleasedHomeWorkList(classId);
	 * modelMap.put("releasedHomeWorkList", releasedHomeWorkList); return
	 * "student/pages/index"; }
	 */

	@RequestMapping(value = "joinClassPage.htm", method = RequestMethod.GET)
	public String joinClassPage(HttpServletRequest request, ModelMap modelMap) {
		return "student/pages/joinClasses";
	}

	@RequestMapping(value = "joinClasses.json", method = RequestMethod.POST)
	@ResponseBody
	public JsonVo<String> joinClasses(HttpServletRequest request,
			@RequestParam(value = "classCode") String classCode) {
		// 老师加入到对应的班级
		User user = (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);

		JsonVo<String> json = new JsonVo<String>();
		UserClasses existUserClasses = systemUserService
				.getUserClassesByUserId(user.getUserId());
		Classes classes = systemUserService.getClassesByClassCode(classCode);

		try {
			if (existUserClasses != null) {
				json.getErrors().put("classCode", "已加入此班级，无需重复加入");
			} else if (classes == null) {
				json.getErrors().put("classCode", "班级邀请码错误");
			}
			// 检测校验结果
			validate(json);
			UserClasses userClasses = new UserClasses(user.getUserId(),
					classes.getClassId(), null, null);
			int result = systemUserService.joinClasses(userClasses);
			List<String> list = new ArrayList<String>();
			list.add(classes.getClassId());
			user.setClassIdList(list);
			request.getSession()
					.setAttribute(SystemConstant.SESSION_USER, user);
			json.setResult(result > 0 ? true : false);
		} catch (Exception e) {
			json.setResult(false);
			json.setMsg(e.getMessage());
		}

		return json;
	}

	@RequestMapping(value = "download.json", method = { RequestMethod.GET })
	public static void download(HttpServletRequest request,
			HttpServletResponse response, String filePath, String contentType,
			String fileName) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		String downLoadPath = SystemConstant.COLLEGE_CCOS_ROOT + filePath;// order_文件名.后缀

		long fileLength = new File(downLoadPath).length();

		response.setContentType(contentType);
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));

		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}

	@RequestMapping(value = "myReleasedHomeWorkStatus/update.json", method = RequestMethod.POST)
	@ResponseBody
	public JsonVo<String> updateReleasedHomeWorkStatus(
			HttpServletRequest request,
			ModelMap modelMap,
			@RequestParam(value = "jobLineId") String jobLineId,
			@RequestParam(value = "submitStatus") SubmitStatusConstant.SubmitStatus submitStatus) {
		JobLine jobLine = new JobLine();
		jobLine.setJobLineId(jobLineId);
		jobLine.setUpdateDate(new Date());
		jobLine.setSubmitStatus(new SubmitStatusConstant()
				.convertToIntValue(submitStatus));
		int num = commonStuAdminService.updateJobLineStatusById(jobLine);

		JsonVo<String> json = new JsonVo<String>();
		if (num > 0) {
			json.setResult(true);
		} else {
			json.setResult(false);
		}
		return json;
	}

	/**
	 * 附件上传
	 */
	@ResponseBody
	@RequestMapping(value = "jobLineAttachment/upload.json", method = RequestMethod.POST)
	public String upload(@RequestParam(value = "file") MultipartFile file,
			@RequestParam(value = "jobLineId") String jobLineId,
			HttpServletRequest request) {
		try {
			User user = (User) request.getSession().getAttribute(
					SystemConstant.SESSION_USER);
			systemUserService.addUploadFile(file,file.getOriginalFilename(), jobLineId,AttachmentConstant.Kind.jobOrderLineFile,user.getUserId());
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (UploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject json = new JSONObject();
		return json.toString();
	}
	
	/**
	 * 附件上传
	 */
	@ResponseBody
	@RequestMapping(value = "jobLineAttachment/query.json", method = RequestMethod.GET)
	public String upload(@RequestParam(value = "jobLineId") String jobLineId,
			HttpServletRequest request) {
		List<Attachment> attachmentList = null;
		try {
			attachmentList = systemUserService.getJobLineAttachmentList(jobLineId,AttachmentConstant.Kind.jobOrderLineFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		
		for(Attachment attachment:attachmentList){
			attachment.setSize(Math.round(attachment.getSize() / 1024));
		}
		JSONObject json = new JSONObject();
		
		json.put("attachmentList", attachmentList);
		return json.toString();
	}
	
	
	/**
	 * @author 彻底删除文件
	 * @throws ArticleNotFoundException
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "jobLineAttachment/delete.json", method = RequestMethod.POST)
	public JsonVo<String> deleteFile(
			@RequestParam(value = "attachmentId") long attachmentId) {
		JsonVo<String> json = new JsonVo<String>();
		try {
			Attachment attachment = systemUserService
					.getAttachmentById(attachmentId);
			systemUserService.deleteAttachment(attachmentId,
					attachment.getPath());
		} catch (Exception e) {
			json.setResult(false);
		}
		json.setResult(true);
		return json;
	}
	

	public static String getDateSecondsValue() {
		String dateStr = null;
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");

		dateStr = sdf.format(now);
		return dateStr;
	}
	
	
	

}
